<?php

namespace app\api\controller;

use app\common\controller\UnLogin;
use app\common\service\UserService as User;
use app\common\service\PurseService;
use think\Db;

class Register extends UnLogin {

	private $pid=0;
	private $reg_type = [1];
	
	public function initialize() {

		parent::initialize();

		//注册ip防刷限制
		// $ip_limit = cache($this->ip.'/Register');
		// $time = time();
		// if(!empty($ip_limit)){
		// 	if($ip_limit['num'] > 10){
		// 		$this->retData(1, '接口调用频繁，请一分钟后再试');
		// 	} else {
		// 		$num = $ip_limit['num']+1;
		// 		if ($num < 10) {
		// 			$experi = $time-$ip_limit['time'];
		// 			cache($this->ip.'/Register',['num'=>$num,'time'=>$time],$experi);	
		// 		} else {
		// 			cache($this->ip.'/Register',['num'=>$num,'time'=>$time],60);	
		// 		}
		// 	}
		// } else {
		// 	cache($this->ip.'/Register',['num'=>1,'time'=>$time],60);
		// }	
	}

	/*
	手机号码注册
	*/
	public function regByPhone(){
		if (!in_array(1, $this->reg_type)) {
			$this->retData(1, '手机号码注册暂未开放');
		}
		$phone       = P('phone');
		$username    = P('username');
		$password    = P('password');
		$paypass     = P('paypass');
		$rid         = P('rid')?:'';
		$code        = P('code');
		$quhao       = P('quhao') ?: '86';
		if (empty($phone)) {
			$this->retData(1, '缺少参数手机号码(phone)');
		}
		if (empty($password)) {
			$this->retData(1, '缺少参数登录密码(password)');
		}
		// if (empty($paypass)) {
		// 	$this->retData(1, '缺少参数交易密码(paypass)');
		// }
		if (empty($code)) {
			$this->retData(1, '缺少参数手机验证码(code)');
		}


		// if (!preg_match("/^1[345789]{1}\d{9}$/", $phone)) {
		// 	$this->retData(1, '手机号码错误');
		// }
		$match_password = '/^[0-9_a-zA-Z]{8,20}$/';
		if (!preg_match($match_password, $password)) {
			$this->retData(1, '登录密码8-20位,且只能为字母数字下划线组合');
		}
		$match_paypass = '/^[0-9]{6}$/';
		if (!preg_match($match_paypass, $paypass)) {
			// $this->retData(1, '交易密码为6位纯数字');
		}

		$phone_verify = model('UserModel')->infoByPhone($phone);
		if ($phone_verify) {
			$this->retData(1, '手机号码已被注册，请更换手机号码！');
		}
		$username_verify = model('UserModel')->infoByUsername($username);
		if ($username_verify) {
			$this->retData(1, '该账号已被注册，请更换账号！');
		}
		
		// $phone_count = model('UserModel')->countPhone($phone);
		// if ($phone_count >= C('register_phone_max')) {
		// 	$this->retData(1, '手机号码注册已达上限！');
		// }
		//短信开关
		if (C('sms_verify_button') == 1) {
			$veri_code = model('PhoneCodeModel')->getPhoneCode($phone, 1);
			if ($code != $veri_code) {
				$this->retData(1, '验证码错误或者已过期');
			}
		}
		//邀请码
		$invite_code = P('invite_code');
		if ($invite_code) {
			$p_info = model('UserModel')->idByInviteCode($invite_code);
			if (!empty($p_info)) {
				$pid = $p_info['id'];
			} else {
				$this->retData(1, '邀请码错误，请联系上级');
			}
		} else {
			//邀请码开关
			if (C('register_is_invite_code') != 0) {
				$this->retData(1, '缺少参数邀请码(invite_code)');
			} else {
				$pid = 0;
			}
		}	
		$this->pid = $pid;
		$data = [
			'username' =>$username ?: $phone,
			'quhao'    =>$quhao,
			'phone'    =>$phone,
			'mail'     =>'',
			'pid'      =>$this->pid,
			'position' =>0,
			'jdid'     =>0,
			'rid'      =>$rid,
			'password' =>$password,
			'paypass'  =>$paypass,
			'avatar'   =>'',
		];
		$res = User::addUser($data);
		if ($res) {
			$this->retData(0, '注册成功', $res);
		} else {
			$this->retData(1, '注册失败');
		}
	}

	/*
	邮箱注册
	 */
	public function regByMail(){
		if (!in_array(2, $this->reg_type)) {
			$this->retData(1, '邮箱注册暂未开放');
		}
		$username    = P('username');
		$mail        = P('mail');
		$password    = P('password');
		$paypass     = P('paypass');
		$rid     = P('rid')?:'';
		$code        = P('code');
		if (empty($mail)) {
			$this->retData(1, '缺少参数邮箱(mail)');
		}
		if (empty($password)) {
			$this->retData(1, '缺少参数登录密码(password)');
		}
		if (empty($paypass)) {
			$this->retData(1, '缺少参数交易密码(paypass)');
		}
		if (empty($code)) {
			$this->retData(1, '缺少参数邮箱验证码(code)');
		}

		if (!preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9]+\.[a-zA-Z]+(\.[a-zA-Z]+)?$/", $mail)) {
			$this->retData(1, '邮箱格式错误');
		}
		$match_password = '/^[0-9_a-zA-Z]{6,20}$/';
		if (!preg_match($match_password, $password)) {
			$this->retData(1, '登录密码8-20位,且只能为字母数字下划线组合');
		}
		$match_paypass = '/^[0-9]{6}$/';
		if (!preg_match($match_paypass, $paypass)) {
			$this->retData(1, '交易密码为6位纯数字');
		}
		$mail_verify = model('UserModel')->infoByMail($mail);
		if ($mail_verify) {
			$this->retData(1, '邮箱已被注册，请更换邮箱！');
		}
		if (C('mail_verify_button') == 1) {
			$veri_code = model('MailCodeModel')->getMailCode($mail, 1);
			if ($code != $veri_code) {
				$this->retData(1, '验证码错误或者已过期');
			}
		}
		//邀请码
		$invite_code = P('invite_code');
		if ($invite_code) {
			$p_info = model('UserModel')->idByInviteCode($invite_code);
			if (!empty($p_info)) {
				$pid = $p_info['id'];
			} else {
				$this->retData(1, '邀请码错误，请联系上级');
			}
		} else {
			//邀请码开关
			if (C('register_is_invite_code') != 0) {
				$this->retData(1, '缺少参数邀请码(invite_code)');
			} else {
				$pid = 0;
			}
		}	
		$this->pid = $pid;
		$data = [
			'username' =>$username ?: $mail,
			'quhao'    =>'86',
			'phone'    =>'',
			'mail'     =>$mail,
			'pid'      =>$this->pid,
			'position' =>0,
			'rid'      =>$rid,
			'jdid'     =>0,
			'password' =>$password,
			'paypass'  =>$paypass,
			'avatar'   =>'',
		];
		$res = User::addUser($data);
		if ($res) {
			$this->retData(0, '注册成功', $res);
		} else {
			$this->retData(1, '注册失败');
		}
	}

	/*
	用户名注册
	 */
	public function regByUsername(){
		if ($this->reg_type != 3) {
			$this->retData(1, '用户名注册暂未开放');
		}
		$username    = P('username');
		$password    = P('password');
		$paypass     = P('paypass');
		$rid         = P('rid');
		if (empty($username)) {
			$this->retData(1, '缺少参数用户名(username)');
		}
		if (empty($password)) {
			$this->retData(1, '缺少参数登录密码(password)');
		}
		if (empty($paypass)) {
			$this->retData(1, '缺少参数交易密码(paypass)');
		}
		if (empty($rid)) {
			$this->retData(1, '缺少参数设备号(rid)');
		}
		if (substr($username, 0,2) != '0x' || strlen($username) != '32') {
			$this->retData(1,'地址有误');
		}
		$match_password = '/^[0-9_a-zA-Z]{32}$/';
		if (!preg_match($match_password, $username)) {
			$this->retData(1, '地址有误');
		}
		$match_password = '/^[0-9_a-zA-Z]{6,20}$/';
		if (!preg_match($match_password, $password)) {
			$this->retData(1, '登录密码8-20位,且只能为字母数字下划线组合');
		}
		$match_paypass = '/^[0-9]{6}$/';
		if (!preg_match($match_paypass, $paypass)) {
			$this->retData(1, '交易密码为6位纯数字');
		}
		$username_verify = model('UserModel')->infoByUsername($username);
		if ($username_verify) {
			$this->retData(1, '该账号已被注册，请更换账号！');
		}
		$rid_num = C('rid_num');
		$rid_verify = model('UserModel')->infoByRid($rid);
		if ($rid_verify >= $rid_num) {
			$this->retData(1, '单台设备最多注册'.$rid_num.'个账号');
		}
		//邀请码
		$invite_code = P('invite_code');
		if ($invite_code) {
			$p_info = model('UserModel')->idByInviteCode($invite_code);
			if (!empty($p_info)) {
				$pid = $p_info['id'];
			} else {
				$this->retData(1, '邀请码错误，请联系上级');
			}
		} else {
			//邀请码开关
			if (C('register_is_invite_code') != 0) {
				$this->retData(1, '缺少参数邀请码(invite_code)');
			} else {
				$pid = 0;
			}
		}	
		$this->pid = $pid;
		$data = [
			'username' =>$username,
			'quhao'    =>'86',
			'phone'    =>'',
			'mail'     =>'',
			'pid'      =>$this->pid,
			'position' =>0,
			'jdid'     =>0,
			'password' =>$password,
			'paypass'  =>$paypass,
			'avatar'   =>'',
			'rid'      =>$rid,
		];
		$res = User::addUser($data);
		if ($res) {
			$this->retData(0, '注册成功', $res);
		} else {
			$this->retData(1, '注册失败');
		}
	}


	/*
	钱包注册
	*/
	public function regByWallet(){
		if ($this->reg_type != 4) {
			$this->retData(1, '钱包注册暂未开放');
		}
		$password    = P('password')?:"a1234567";
		$username    = P('username')?:"a1234567";
		if (empty($username)) {
			$this->retData(1, '缺少参数用户名(username)');
		}
		if (empty($password)) {
			$this->retData(1, '缺少参数登录密码(password)');
		}
		$match_password = '/^[0-9_a-zA-Z]{8,20}$/';
		if (!preg_match($match_password, $password)) {
			$this->retData(1, '密码8-20位,且只能为字母数字下划线组合');
		}	
		$username_verify = model('UserModel')->infoByUsername($username);
		if ($username_verify) {
			$this->retData(1, '该钱包名称已被使用，请更换名称！');
		}
		//邀请码
		$invite_code = P('invite_code')?:"000001";
		if ($invite_code) {
			$p_info = model('UserModel')->idByInviteCode($invite_code);
			if (!empty($p_info)) {
				$pid = $p_info['id'];
			} else {
				$this->retData(1, '邀请码错误，请联系上级');
			}
		} else {
			//邀请码开关
			if (C('register_is_invite_code') != 0) {
				$this->retData(1, '缺少参数邀请码(invite_code)');
			} else {
				$pid = 0;
			}
		}
		$this->pid = $pid;
		$position = 0;
		$jdid     = 0;
		$data     = [
			'username' =>$username,
			'quhao'    =>'',
			'phone'    =>'',
			'mail'     =>'',
			'pid'      =>$this->pid,
			'position' =>$position,
			'jdid'     =>$jdid,
			'password' =>$password,
			'paypass'  =>'',
			'avatar'   =>'',
			'rid'      =>'',
		];
		$res = User::addUser($data);
		if ($res) {
			$this->retData(0, '注册成功', $res);
		} else {
			$this->retData(1, '注册失败');
		}
	}

	
	/*
	导入账户
	 */	
	// public function dr(){
	// 	$type      = P('type')?:1;
	// 	$data      = P('data');
	// 	$username  = P('username');
	// 	$password  = P('password');
	// 	if (empty($username)) {
	// 		$this->retData(1, '缺少参数用户名(username)');
	// 	}
	// 	if (empty($password)) {
	// 		$this->retData(1, '缺少参数登录密码(password)');
	// 	}
	// 	if (empty($data)) {
	// 		$this->retData(1, '缺少参数数据(data)');
	// 	}
	// 	$match_password = '/^[0-9_a-zA-Z]{8,20}$/';
	// 	if (!preg_match($match_password, $password)) {
	// 		$this->retData(1, '密码8-20位,且只能为字母数字下划线组合');
	// 	}
	// 	if (!in_array($type, [1,2,3])) {
	// 		$this->retData(1, 'system error');
	// 	}
	// 	switch ($type) {
	// 		case '1':
	// 			$name = 'words';
	// 			$data = explode(" ", $data);
	// 			$data = implode(",", $data);
	// 			$remark = '助记词';
	// 			break;
	// 		case '2':
	// 			$name   = 'keystore';
	// 			$remark = 'keystore';
	// 			$data = str_replace('&quot;', '"', $data);
	// 			break;
	// 		case '3':
	// 			$name = 'private_key';
	// 			$remark = '私钥';
	// 			break;
	// 		default:
	// 			# code...
	// 			break;
	// 	}
	// 	$account = Db::table('tp_user_recovery')->where($name,$data)->find();
	// 	if (empty($account)) {
	// 		 $this->retData(1, $remark.'不存在');
	// 	}
	// 	$user_info = Db::table('tp_user')->where('id',$account['uid'])->find();
	// 	if ($user_info['username'] != $username) {
	// 		$this->retData(1, '钱包名称有误');
	// 	}
		
	// 	Db::startTrans();
	// 	$uid = $user_info['id'];
	// 	if ($type == 2) {
	// 		if ($user_info['password'] != md5($password)) {
	// 			$this->retData(1, '钱包密码错误');
	// 		}
	// 	} else {
	// 		//更新密码和私钥
	// 		if ($user_info['password'] != md5($password)) {
	// 			$res1 = Db::table('tp_user')->where('id',$account['uid'])->update(['password'=>md5($password)]);
	// 			$res2 = Db::table('tp_user_recovery')->where('uid',$account['uid'])->update(['password'=>md5($password)]);
	// 			if (!$res1 || !$res2) {
	// 				Db::rollback();
	// 				$this->retData(1, '导入失败');
	// 			}
	// 		}
	// 	}
	// 	//设置token
	// 	$token    = model('TokenModel')->setToken($uid);

	// 	//代币钱包地址
	// 	$address  = Db::table('tp_user_wallet_address')->where('uid',$uid)->where('cid',10)->value('address');

	// 	if($uid && $token && $address){
	// 		Db::commit();
	// 		$this->retData(0, '导入成功', ['uid'=>$uid,'words'=>$account['words'],'token'=>$token,'address'=>$address,'username'=>$username]);
	// 	} else {
	// 		Db::rollback();
	// 		$this->retData(1, '导入失败');
	// 	}		
	// }
	// 
		//导入账户
	public function dr(){
		$type      = P('type')?:1;
		$data      = P('data');
		$username  = P('username');
		$password  = P('password');
		if (empty($username)) {
			$this->retData(1, '缺少参数用户名(username)');
		}
		if (empty($password)) {
			$this->retData(1, '缺少参数登录密码(password)');
		}
		if (empty($data)) {
			$this->retData(1, '缺少参数数据(data)');
		}
		$match_password = '/^[0-9_a-zA-Z]{8,20}$/';
		if (!preg_match($match_password, $password)) {
			$this->retData(1, '密码8-20位,且只能为字母数字下划线组合');
		}
		if (!in_array($type, [1,2,3])) {
			$this->retData(1, 'system error');
		}
		switch ($type) {
			case '1':
				$name = 'words';
				$data = explode(" ", $data);
				$data = implode($data, ",");

				$data1 = $data;
				break;
			case '2':
				$name = 'keystore';
				$data = str_replace('&quot;', '"', $data);
				$data1 = md5($data);
				
				break;
			case '3':
				$name = 'private_key';
				$data1 = $data;
				break;
			default:
				# code...
				break;
		}

		$res = PurseService::dr($type,$data,$password);
		if (!$res) {
			$this->retData(1, '导入失败1');
		}

		$address = $res['address'];
		$words   = $res['remark'];
		$uid = Db::table('tp_user_wallet_address')->where('wid',10)->where('address',$address)->value('uid');
		if (!$uid) {
			$this->retData(1, '导入失败2');
		}
		$user_info = Db::table('tp_user')->where('id',$uid)->find();

		if ($user_info['username'] != $username) {
			$this->retData(1, '钱包名称有误');
		}
		Db::startTrans();
		if ($type == 2) {
			if ($user_info['password'] != md5($password)) {
				$this->retData(1, '钱包密码错误');
			}
		} else {
			//更新密码和私钥
			if ($user_info['password'] != md5($password)) {
				$res1 = Db::table('tp_user')->where('id',$uid)->update(['password'=>md5($password)]);

				$res2 = 1;
				// $res2 = Db::table('tp_user_recovery')->where('uid',$uid)->update(['password'=>md5($password)]);
				if (!$res1 || !$res2) {
					Db::rollback();
					$this->retData(1, '导入失败3');
				}
			}
		}
		//设置token
		$token    = model('TokenModel')->setToken($uid);

		if($uid && $token && $address){
			Db::commit();
			$this->retData(0, '导入成功', ['uid'=>$uid,'words'=>$words,'token'=>$token,'address'=>$address,'username'=>$username]);
		} else {
			Db::rollback();
			$this->retData(1, '导入失败');
		}
	}
}
